package com.eobjectsoft.etranslator.engine;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;


public class TranslateUtils
{
	private static int BUFFER_LENGTH = 1024;
    public static String DEFAULT_CHARTSET = "ISO-8859-1";

    /**
     * send http result
     */
    public static synchronized byte[] getUrlResult(URL url)
        throws IOException
    {
        ByteArrayOutputStream bos;
        URLConnection uc = url.openConnection();
        //set the agent to IE
        uc.setRequestProperty("User-agent", "IE/6.0");
        InputStream inputStream = (InputStream)uc.getContent();
        bos = new ByteArrayOutputStream();
        byte buffer[] = new byte[BUFFER_LENGTH];
        for(int len = 0; (len = inputStream.read(buffer)) > 0;)
            bos.write(buffer, 0, len);

        inputStream.close();
        return bos.toByteArray();
    }

    /**
     * convert bytes to hex string for debug purpose
     */
    public static String toHexString(byte bytes[])
    {
        StringBuffer retString = new StringBuffer();
        for(int i = 0; i < bytes.length; i++)
        {
            retString.append(Integer.toHexString(256 + (bytes[i] & 0xff)).substring(1));
            retString.append(" ");
        }

        return retString.toString();
    }

    public static String getLocaleFileExtension(String fileName, TranslateMode mode)
    {
        if(fileName.lastIndexOf(".") > 0)
        {
            String path = fileName.substring(0, fileName.lastIndexOf("."));
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
            return path + "_" + mode.getTargetLanguage() + "." + extension;
        } else
        {
            return fileName + "_" + mode.getTargetLanguage();
        }
    }

    
}
